package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: wf
 * @Desc:   分类管理
 * @Date: 2022-08-22 18:37:43
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        // 创建分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);

        categoryService.page(pageInfo);

        return R.success(pageInfo);
    }

    /**
     * 功能描述: 新增分类管理
     * @param category
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){

        categoryService.save(category);

        return R.success("新增成功");
    }

    /**
     * 功能描述: 根据id删除分类管理
     * @param id
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @DeleteMapping
    public R<String> delete(Long id){

        categoryService.delete(id);

        return R.success("删除成功");
    }

    /**
     * 功能描述: 修改分类管理
     * @param category
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 功能描述: 根据条件查询分类数据
     * @return com.itheima.reggie.common.R<java.util.List<com.itheima.reggie.entity.Category>>
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(lqw);

        return R.success(categoryList);
    }

}
